import { scanQrcode } from '@/api/order.js';

export const getSign = (config = {}) => {
  const params = {
    scene: config.scene,
  };
  if (config.competition_id) {
    params['competition_id'] = config.competition_id;
  }
  scanQrcode(params)
    .then(data => {
      console.log('---扫码接口返回值--', data);
      config.onSuccess && config.onSuccess(data);
      setTimeout(() => {
        uni.redirectTo({
          url: data.schema,
        });
      }, 200);
    })
    .catch(err => {
      config.onFail && config.onFail(err);
      uni.showToast({
        title: err.msg || err.errMsg || '扫码失败！',
        icon: 'none',
        duration: 2000,
      });
    });
};

export const scanCode = ({ onSuccess, onFail, params = {} } = {}) => {
  // uni.redirectTo(
  //   { url: '/subpackages/sub-3d/pages/bodyReport/index?bmd_report_id=24&bmd_model=vrpro3&from=scan' }
  // );
  // return;
  uni.scanCode({
    success(res) {
      if (res.errMsg === 'scanCode:ok') {
        if ('path' in res && res.path.indexOf('scene')) {
          let scene = res.path.split('=')[1];
          let path = res.path.split('?')[0];
          scene = decodeURIComponent(scene);
          console.log(path + '?' + scene);
          if (path != 'pages/index/index') {
            uni.redirectTo({
              url: '/' + res.path + (scene.indexOf('=') != -1 ? '&' + scene : ''),
            });
          } else {
            if (onSuccess) {
              onSuccess({ scene });
            }
            getSign({ scene, ...params });
          }
        } else if ('path' in res) {
          let path = res.path.split('?')[0];
          if (path != 'pages/index/index') {
            uni.redirectTo({
              url: '/' + res.path,
            });
          }
        }
      }
    },
    fail(err) {
      // uni.showToast({
      //   title: '扫码失败！',
      //   icon: 'none',
      //   duration: 2000,
      // });
      if (onFail) {
        onFail(err);
      }
    },
    complete(res) {
      console.log(res);
    },
  });
};
